package com.ebo.common.smart;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.json.JSONUtil;

import java.net.URL;
import java.nio.charset.Charset;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class LocalDataAddressDataLoader implements AddressDataLoader {

    private static final List<Address> addressList;

    private static final Map<String, Address> addresCodeMap = new ConcurrentHashMap<>();

    static {
        URL url = ResourceUtil.getResource("areaData.json");
        String jsonData = FileUtil.readString(url, Charset.defaultCharset());
        addressList = JSONUtil.parseArray(jsonData).toList(Address.class);

        initAreaMap(addressList);
    }


    private static void initAreaMap(List<Address> addressList) {
        if (CollUtil.isEmpty(addressList)) {
            return;
        }
        for (Address address : addressList) {
            if (address.getCode() != null) {
                addresCodeMap.put(address.getCode(), address);
            }
            initAreaMap(address.getChildren());
        }
    }


    @Override
    public List<Address> loadData() {
        return addressList;
    }


    public static Address getByCode(String code) {
        return addresCodeMap.get(code);
    }

}
